package com.my.netty.thread;

import cn.hutool.core.lang.Console;
import cn.hutool.cron.CronUtil;
import cn.hutool.cron.task.Task;
import cn.hutool.json.JSONUtil;
import com.my.netty.NettyPoolClient;
import com.my.netty.util.Const;
import com.my.netty.vo.User;
import io.netty.channel.Channel;
import io.netty.channel.pool.SimpleChannelPool;
import io.netty.util.concurrent.Future;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class RunClient extends Thread {


    private int num = 0;

    private NettyPoolClient client;

    public RunClient(int num, NettyPoolClient client) {
        this.num = num;
        this.client = client;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            final SimpleChannelPool pool = client.poolMap.get(Const.remoteAddr);
            Future<Channel> f = pool.acquire();
            Channel channel = f.get(60, TimeUnit.SECONDS);
            User user = new User();
            user.setAddress("121212");
            user.setAge("12");
            user.setName("dsfdsfsdfdsfsdf");
            String msg = JSONUtil.toJsonStr(user);
            channel.writeAndFlush(msg + "\r\n");
            pool.release(channel);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } finally {
        }
 /*       f.addListener(new GenericFutureListener() {
            @Override
            public void operationComplete(Future future) throws Exception {
                if (future.isSuccess()) {
                    Channel channel = (Channel) future.getNow();
                    channel.writeAndFlush("fuck you\r\n");
                    pool.release(channel);
                }
            }
        });*/
    }


    public static void main(String[] args) {
        NettyPoolClient client = new NettyPoolClient();
        client.build();

        CronUtil.schedule("*/2 * * * * *", new Task() {
            @Override
            public void execute() {
                Console.log("Task excuted.");
            }
        });

        CronUtil.setMatchSecond(true);
        CronUtil.start();
     /*   for (int i = 0; i <= 10000; i++) {
            RunClient runClient = new RunClient(i, client);
            runClient.start();
        }*/
    }

}
